package com.csj.mvvm.ui.base

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.csj.mvvm.widget.clicks
import java.lang.reflect.ParameterizedType


/**
 * 通过传入ViewBinding，不再需要写具体xml资源，省略onBindViewHolder中findviewById
 * 注意点：item的最外层父布局高度要设为wrap_content，(子布局设置固定宽高有效)
 * 如果item有需求要设置为固定宽高，可以在子类的convert方法里，通过代码设置
 */
abstract class BaseAdapter2<VB : ViewDataBinding, T>(
    var mContext: FragmentActivity,
    var listDatas: ArrayList<T> = ArrayList()
) : RecyclerView.Adapter<BaseViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
        val vb: ViewDataBinding = DataBindingUtil.inflate(
            LayoutInflater.from(parent.context),
            getLayoutId(),
            parent,
            false
        )
        vb.lifecycleOwner = mContext
        vb.root.layoutParams = RecyclerView.LayoutParams(
            RecyclerView.LayoutParams.MATCH_PARENT,
            RecyclerView.LayoutParams.WRAP_CONTENT
        )
        return BaseViewHolder(vb, vb.root)
    }

    override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
        holder.itemView.clicks {
            itemClick?.let { it -> it(holder.itemView, position) }
        }
        holder.itemView.setOnLongClickListener {
            itemLongClick?.let { il -> il(holder.itemView, position) }
            true
        }

        convert(holder.v as VB, listDatas[position], position)
    }

    abstract fun getLayoutId(): Int

    abstract fun convert(v: VB, t: T, position: Int)

    override fun getItemCount(): Int {
        return listDatas.size
    }


    open var itemClick: ((View, Int) -> Unit)? = null
    private var itemLongClick: ((View, Int) -> Unit)? = null


    open fun itemClick(itemClick: (View, Int) -> Unit) {
        this.itemClick = itemClick
    }

    open fun itemLongClick(itemLongClick: (View, Int) -> Unit) {
        this.itemLongClick = itemLongClick
    }

    open fun addData(data: T?) {
        if (data != null) {
            listDatas.add(data)
            notifyDataSetChanged()
        }
    }

    open fun addData(newData: Collection<T>?) {
        if (newData != null && newData.isNotEmpty()) {
            listDatas.addAll(newData)
            notifyDataSetChanged()
        }
    }

    open fun replaceData(data: Collection<T>?) {
        listDatas.clear()
        data?.let { listDatas.addAll(it) }
        notifyDataSetChanged()
    }
}
